package net_UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2023-02-16
 * Time: 16:42
 */
public class UdpEchoServer {
    private DatagramSocket socket=null;

    //参数的端口表示服务器要绑定的端口号
    //这个IP一般是主机IP，不用写
    public UdpEchoServer(int port) throws SocketException {
        //服务器指定端口是为了客户端方便找到服务器
        socket=new DatagramSocket(port);
    }

    //通过这个方法启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //循环的处理里面每一次请求
            //1.读取请求并解析
            //把这个 DatagramPacket 对象转为字符串，方便去打印
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request=new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求计算响应
            String response=process(request);
            //3.把响应写回客户端
            // requestPacket.getSocketAddress():拿到客户端的IP和端口
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //4.打印一个日志，记录当前情况
            //requestPacket.getAddress().toString(): 拿到客户端的IP地址
            //requestPacket.getPort(): 拿到客户端的端口号
            System.out.printf("[%s:%d] req: %s; resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(9090);
        server.start();
    }

}
